﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using YiMeiJiaService.IService;
using YiMeiJiaService.Assembly;
using YiMeiJiaLibModel.Assembly;
using YiMeiJiaLibModel.Business;
using System.Text.Json.Serialization;
using Newtonsoft.Json;
using System.Dynamic;
using YiMeiJiaService.Assembly.DB;
namespace YiMeiJiaService.Service
{
    public class Account : IAcccount
    {
        public async Task<ApiResponse<JwtTokenResponseJson, CoreCmsUser>> Login(string mobile, string code)
        {
            var response = await _HttpClient.Action<JwtTokenResponseJson, CoreCmsUser>("smsLogin",
                                                new
                                                {
                                                    mobile ,
                                                    platform = 1,
                                                    code = code
                                                });
            if (response.status)
            {
                var data = response.data;
                var otherData = response.otherData;
                //var jsonDynamic = JsonConvert.DeserializeObject<CoreCmsUser>(Convert.ToString(otherData));
                var id = otherData.id;// Convert.ToInt32(jsonDynamic.id) ;
                var authorize = new AdnroidTokens();
                authorize.Token = data.token;
                authorize.EffecTime =  DateTime.Now.AddSeconds(data.expires_in);
                authorize.UserId = id;
                authorize.Mobile = Convert.ToString(otherData.mobile);
                authorize.DeviceId = Guid.NewGuid().ToString();


                var db =await YMJLifeSqlite.Db();
                var DeviceUser = await db.Table<AdnroidTokens>().FirstOrDefaultAsync();
                if (DeviceUser != null)
                {
                    authorize.DeviceId = DeviceUser.DeviceId;
                    await db.UpdateAsync(authorize);
                }
                else
                {
                    await db.InsertAsync(authorize);
                }
                

                return response;
            }
            else
            {
                return response;
            }
            //return Task<bool>.FromResult(true);

        }
    }
}
